<template>
  <div class="trajectory-player">
    <div class="player-section">
      <h3>轨迹回放</h3>
      
      <!-- 用户查询 -->
      <div class="player-item">
        <el-input
          v-model="searchName"
          placeholder="请输入用户名"
          style="width: 140px"
        ></el-input>
        
        <el-button @click="searchUsers" type="primary">
          搜索用户
        </el-button>
      </div>
      
      <!-- 用户选择 -->
      <div class="player-item" v-if="userList.length > 0">
        <el-select
          v-model="selectedUserId"
          placeholder="请选择用户"
          style="width: 220px"
          @change="handleUserChange"
        >
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.name"
            :value="user.id"
          >
            <span style="float: left">{{ user.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ user.id }}</span>
          </el-option>
        </el-select>
      </div>
      
      <!-- 轨迹查询按钮 -->
      <div class="player-item">
        <el-button 
          @click="openQueryDialog" 
          :disabled="!selectedUserId"
          type="primary"
        >
          轨迹查询
        </el-button>
      </div>
      
      <!-- 回放控制 -->
      <div class="player-item" v-if="hasTrajectory">
        <el-button 
          @click="playTrajectory" 
          :disabled="isPlaying"
          type="success"
          icon="el-icon-video-play"
        >
          播放
        </el-button>
        
        <el-button 
          @click="stopTrajectory" 
          :disabled="!isPlaying"
          type="danger"
          icon="el-icon-video-pause"
        >
          停止
        </el-button>
        
        <el-button 
          @click="resetTrajectory" 
          icon="el-icon-refresh-right"
        >
          重置
        </el-button>
      </div>
      
      <!-- 播放速度控制 -->
      <div class="player-item" v-if="hasTrajectory">
        <span class="label">播放速度:</span>
        <el-slider
          v-model="playbackSpeed"
          :min="0.1"
          :max="2"
          :step="0.1"
          :format-tooltip="formatSpeed"
          style="width: 180px"
          @change="handleSpeedChange"
        ></el-slider>
      </div>
    </div>
    
    <!-- 轨迹查询对话框 -->
    <el-dialog
      v-model="showQueryDialog"
      title="轨迹查询"
      width="500px"
    >
      <el-form :model="queryParams" label-width="100px">
        <el-form-item label="用户ID">
          <el-input v-model="queryParams.id" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="用户姓名">
          <el-input v-model="queryParams.name" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="queryParams.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="queryParams.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="生成路径">
          <el-radio-group v-model="queryParams.createPath">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="交通方式" v-if="queryParams.createPath">
          <el-select
            v-model="queryParams.trafficMode"
            placeholder="请选择交通方式"
            style="width: 100%"
          >
            <el-option
              v-for="option in trafficModeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showQueryDialog = false">取消</el-button>
          <el-button type="primary" @click="queryTrajectory">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, inject, computed, onMounted, watch } from 'vue';
import { useTrajectory } from '@/hooks/useTrajectory';
import userService from '@/services/user.service';
import { ElMessage, ElLoading } from 'element-plus';
import { useTrajectoryStore } from '@/stores/modules/trajectory';

// 注入地图相关对象
const map = inject('map');
const sourceFeatures = inject('sourceFeatures');
const lineString = inject('lineString');

// 获取轨迹状态管理
const trajectoryStore = useTrajectoryStore();

// 用户搜索和选择
const searchName = ref('');
const selectedUserId = ref('');
const userList = ref([]);

// 查询参数
const showQueryDialog = ref(false);
const queryParams = ref({
  id: '',
  name: '',
  startTime: '',
  endTime: '',
  pageNo: 1,
  pageSize: 100,
  createPath: false,
  trafficMode: 'car'
});

// 交通方式选项
const trafficModeOptions = userService.getTrafficModeOptions();

// 获取轨迹控制钩子
const {
  isPlaying,
  path,
  pathPoint,
  userPositionData,
  myplanImg,
  loadUserTrajectory,
  startAnimation,
  stopAnimation,
  resetAnimation,
  setAnimationSpeed
} = useTrajectory(map, sourceFeatures);

// 播放控制
const playbackSpeed = ref(1);
const hasTrajectory = computed(() => path.value && path.value.length > 1);

// 监听状态变化，同步到Pinia
watch(isPlaying, (newValue) => {
  trajectoryStore.setPlaying(newValue);
});

watch(path, (newValue) => {
  if (newValue && newValue.length > 0) {
    trajectoryStore.setTrajectoryData(newValue);
  }
});

watch(playbackSpeed, (newValue) => {
  trajectoryStore.setCurrentSpeed(newValue);
});

// 组件挂载时，从Pinia恢复状态
onMounted(() => {
  // 恢复播放速度
  if (trajectoryStore.getCurrentSpeed) {
    playbackSpeed.value = trajectoryStore.getCurrentSpeed;
  }
  
  // 恢复查询参数
  if (trajectoryStore.getQueryParams) {
    const storeParams = trajectoryStore.getQueryParams;
    queryParams.value = {
      ...queryParams.value,
      ...storeParams
    };
  }
});

/**
 * 搜索用户
 */
async function searchUsers() {
  if (!searchName.value) {
    ElMessage.warning('请输入用户名');
    return;
  }
  
  const loading = ElLoading.service({
    text: '正在搜索用户...'
  });
  
  try {
    const result = await userService.searchUsers({ name: searchName.value });
    
    if (result.success) {
      userList.value = result.data;
      trajectoryStore.setUserList(result.data);
      
      if (userList.value.length === 0) {
        ElMessage.info('未找到匹配的用户');
      } else {
        ElMessage.success(`找到 ${userList.value.length} 个用户`);
      }
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    console.error('搜索用户失败:', error);
    ElMessage.error('搜索用户失败');
  } finally {
    loading.close();
  }
}

/**
 * 处理用户选择变更
 */
function handleUserChange(userId) {
  const user = userService.selectUser(userId);
  
  if (user) {
    // 设置查询参数
    queryParams.value.id = user.id;
    queryParams.value.name = user.name;
    
    // 更新Pinia状态
    trajectoryStore.setSelectedUserId(userId);
    
    ElMessage.success(`已选择用户: ${user.name}`);
  }
}

/**
 * 打开轨迹查询对话框
 */
function openQueryDialog() {
  if (!selectedUserId.value) {
    ElMessage.warning('请先选择用户');
    return;
  }
  
  showQueryDialog.value = true;
  trajectoryStore.setQueryDialogVisible(true);
}

/**
 * 查询轨迹数据
 */
async function queryTrajectory() {
  // 验证时间范围
  if (!queryParams.value.startTime || !queryParams.value.endTime) {
    ElMessage.warning('请选择起止时间');
    return;
  }
  
  showQueryDialog.value = false;
  trajectoryStore.setQueryDialogVisible(false);
  
  const loading = ElLoading.service({
    text: '正在加载轨迹数据...'
  });
  
  try {
    // 使用userService中的参数进行查询
    Object.assign(userService.queryParams, queryParams.value);
    
    // 更新Pinia状态
    trajectoryStore.setQueryParams(queryParams.value);
    
    // 加载轨迹数据
    const result = await loadUserTrajectory(userService.queryParams, lineString.value);
    
    if (result.success) {
      if (hasTrajectory.value) {
        ElMessage.success(`已加载 ${path.value.length} 个轨迹点`);
      } else {
        ElMessage.warning('轨迹点数据不足，无法播放');
      }
    } else {
      ElMessage.error(result.error || '轨迹数据加载失败');
    }
  } catch (error) {
    console.error('查询轨迹失败:', error);
    ElMessage.error('查询轨迹失败');
  } finally {
    loading.close();
  }
}

/**
 * 播放轨迹
 */
function playTrajectory() {
  if (!hasTrajectory.value) {
    ElMessage.warning('没有可播放的轨迹数据');
    return;
  }
  
  startAnimation();
  trajectoryStore.setPlaying(true);
  ElMessage.success('开始播放轨迹');
}

/**
 * 停止轨迹播放
 */
function stopTrajectory() {
  stopAnimation();
  trajectoryStore.setPlaying(false);
  ElMessage.info('轨迹播放已停止');
}

/**
 * 重置轨迹
 */
function resetTrajectory() {
  resetAnimation();
  trajectoryStore.resetTrajectoryState();
  ElMessage.info('轨迹已重置');
}

/**
 * 格式化速度显示
 */
function formatSpeed(value) {
  return `${value}x`;
}

/**
 * 处理速度变更
 */
function handleSpeedChange(value) {
  // 速度越大，间隔越小
  const interval = Math.round(300 / value);
  setAnimationSpeed(interval);
  trajectoryStore.setCurrentSpeed(value);
}
</script>

<style scoped>
.trajectory-player {
  position: absolute;
  top: 10px;
  left: 330px;
  z-index: 1000;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 260px;
}

.player-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.player-section h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}

.player-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.label {
  min-width: 70px;
  font-size: 14px;
}
</style> 